<template>
  <base-breadcrumb :title="$route.meta.title">
  <a-row
      :gutter="10"
      class="page-height"
    >
      <!-- 树搜索 -->
      <a-col
        :span="6"
        class="permission-collapsed"
        :class="{ 'permission-tree-collapsed': collapsed }"
      >
        <a-card
          :style="{ border: collapsed ? 'none' : 'border: 1px solid #e8e8e8' }"
          class="page-height-tree"
        >
          <title-name title="组织架构" />
          <PermissionTreeOrganization
            :collapsed.sync="collapsed"
            @select="handleSelect"
          />
        </a-card>
      </a-col>
      <a-col
        :span="18"
        class="permission-collapsed page-height-list-wrapper"
        :style="collapsed ? 'width:calc(100% - 10px)' : ''"
      >
        <searchData :key="searchOption[0].type" ref="searchData" :search-data="searchOption" @search="search" />
        <a-card :bordered="false">
          <list-table
            :defaultLoad="false"
            ref="table"
            :page-keys="['pageNum', 'pageSize','total']"
            size="default"
            rowKey="projectIndex"
            :key="select.projectId"
            :columns="columns"
            :request="loadData"
            show-pagination="auto"
            :statistics-config="{ use: true, statistics, temp }"
            :exportConfig="{ use: true,select: '导出选中',all: '导出全部'}"
            @exportSelect="exportSelect"
            @exportAll="exportAll"
          >
            <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>

            <template slot="examineMonth" slot-scope="text, record, index">
              <span>{{text}}</span>
              <span v-if="record.isOutTime" style="color: #ff0000">（超时自动提交）</span>
            </template>

            <template slot="state" slot-scope="text, record, index">
              <span :style="text == '3' ? { color: '#ff0000' } : {}">{{stateName(text)}}</span>
            </template>
          </list-table>
        </a-card>
      </a-col>
      </a-row>
  </base-breadcrumb>
</template>

<script>

import { searchOption, searchOption1, columns, columns2, columns3 } from './model.js'
import { getPlanExamineMonthExcel, getPlanExamineMonthDetail, getPlanExamineMonthCount, planExamineMonthCommonExport } from '@/api/project/projectPlanningAssessment'
import ExportMould from '@/components/ServiceExportMould'
import PermissionTreeOrganization from './PermissionTreeOrganization'
export default {
  name: 'ProjectRecord',
  components: {
    ExportMould,
    PermissionTreeOrganization
  },
  data() {
    return {
      collapsed: false,
      searchOption,
      columns,
      activeKey: '0',
      total:0,
      exportConfig: getPlanExamineMonthExcel(),
      queryParam: {},
      select: {},
      projectIds: [],
      loadData: (parameter) => {
        if(this.projectIds.length<1) return {data: []}
        if(this.select.tageCode === 'PD' && !this.queryParam.examineYear) {
          this.queryParam.examineYear = this.getData();
          delete this.queryParam.examineMonth
        } 
        if(this.select.tageCode !== 'PD' && !this.queryParam.examineMonth) {
          this.queryParam.examineMonth = this.getData('month');
          delete this.queryParam.examineYear
        }
        const requestParameters = Object.assign({}, parameter, { param: {...this.queryParam, projectIds:this.projectIds} })
        getPlanExamineMonthCount({projectIds:this.projectIds, ...this.queryParam}).then(res=> {
          this.statistics = res.data;
        })
        return getPlanExamineMonthDetail(requestParameters).then((res) => {
          this.total = res.totalSize || 0
          return {code: 200, data: this.datatransformation(res.data.list), ...res.data }
        }).catch((err) => {
          return {
            code: 500,
            err
          }
        })
      },
      temp: () => {
        return (
          <span style="margin-right: 12px">
            节点总数：<span class="totalNum">{this.statistics.allNode || 0} 个</span> |
            应完成节点数：<span class="totalNum" onClick={()=>this.toDetails(1)}>{this.statistics.completedNum || 0} 个</span> |
            逾期未完成节点数：<span class="totalNum" onClick={()=>this.toDetails(2)}>{this.statistics.overdueNum || 0} 个</span> |
            节点完成率：<span>{this.statistics.nodeRatio || 0} %</span>
          </span>
        )
      },
      statistics: {},  // 统计
    }
  },
  computed: {},
  watch: {
    'select.projectId'(newVal, oldVal) {
      // if(newVal && oldVal) return;
      if(newVal) {
        this.searchOption = searchOption1
        this.columns.splice(1, 1, columns3[0])
        setTimeout(()=> {
          this.$refs.searchData.form.setFieldsValue({examineYear: this.getData('year', 'from')})
        },0)
      }else {
        this.searchOption = searchOption
        this.columns.splice(1,1, columns2[0])
        setTimeout(()=> {
          this.$refs.searchData.form.setFieldsValue({examineMonth: this.getData('month', 'from')})
        },0)
      }
    }
  },
  mounted() {
    this.$refs.searchData.form.setFieldsValue({examineYear: this.getData('year', 'from')})
    this.$refs.searchData.form.setFieldsValue({examineMonth: this.getData('month', 'from')})
  },
  methods: {
    search(e) {
      let param = this.$clone(e)
      if(param.examineMonth) {
        let a = param.examineMonth.split('-')
        param.examineMonth = a.join('');
      }
      this.queryParam = {
        ...param
      }
      this.$refs.table.refresh(true)
    },
    handleSelect(node) {
      this.select = node
      if(node.tageCode === 'CO') return;
      this.projectIds = [];
      if(node.tageCode === 'BC' && node.childTree && node.childTree.length) {
        node.childTree.map(item=> {
          if(item.tageCode === 'PD') {
            this.projectIds.push(item.projectId);
          }
        })
      }
      if(node.tageCode === 'PD') {
        this.projectIds.push(node.projectId);
      }
      this.search(this.queryParam);
    },
    toDetails(type) {
      this.$router.push({
        path: '/project/projectPlanningAssessment/monthlySummary/dataDetails',
        query: {
          type,
          ...this.queryParam,
          tageCode: this.select.tageCode
        }
      })
      sessionStorage.setItem('projectIds', JSON.stringify(this.projectIds))
    },
    getData(type, from) {
      var date = new Date()
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      return type === 'month' ? (month > 9 ? (year + '' + month) : (year + '0' + month)) : year + ''
    },
    datatransformation(data) {
      data.map((item, index)=> {
        item.projectIndex = item.projectId+index
        item.planExamineCheckItems.map((ch, i)=> {
          item['problemInfo'+i] = ch.problemInfo
          item['measures'+i] = ch.measures
          item['measuresTime'+i] = ch.measuresTime
          item['effect'+i] = ch.effect
        })
      }) 
      return data
    },
    exportSelect(data) {
      let ids = [], month = [];
      data.map(item=> {
        ids.indexOf(item.projectId) === -1 && ids.push(item.projectId);
        month.indexOf(item.examineMonth) === -1 && month.push(item.examineMonth);
      })
      planExamineMonthCommonExport({projectIds:ids, ...this.queryParam, month}).then(res=> {
        this.handleDownload(res);
      })
    },
    exportAll(data) {
      let ids = [], month = [];
      data.map(item=> {
        ids.indexOf(item.projectId) === -1 && ids.push(item.projectId);
        month.indexOf(item.examineMonth) === -1 && month.push(item.examineMonth);
      })
      planExamineMonthCommonExport({projectIds:ids, ...this.queryParam, month}).then(res=> {
        this.handleDownload(res);
      })
    },
    handleDownload(res){
      const blob = new Blob([res.data])
      const filename = decodeURIComponent(res.headers['content-disposition'].split('filename=')[1])
      console.log(filename)
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob) // 创建下载的链接
      downloadElement.href = href
      downloadElement.download = filename.substring(filename.indexOf("''") + 2) // 获取文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() //点击下载
      document.body.removeChild(downloadElement) //下载完成移除元素
      window.URL.revokeObjectURL(href) //释放blob对象
    },
  }
}
</script>

<style lang="less" scoped>
 ::v-deep .ant-table-row-cell-break-word {
  white-space: pre-line
}
  .totalNum {
    cursor: pointer;
  }
</style>
